package com.lwj.liwanjia.view.activity.address;


import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.AmapAdapter;
import com.lwj.liwanjia.base.BaseActivity;
import com.superrecycleview.superlibrary.adapter.SuperBaseAdapter;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

//地图定位
public class AmapActivity extends BaseActivity implements LocationSource, AMapLocationListener, PoiSearch.OnPoiSearchListener {

    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.map)
    MapView map;
    @BindView(R.id.ed_sousuo)
    EditText edSousuo;
    @BindView(R.id.rl_dizhi)
    SuperRecyclerView rlDizhi;

    private AMap aMap;//地图控制器对象
    private MyLocationStyle myLocationStyle;//定位蓝点
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    //标识，用于判断是否只显示一次定位信息和用户重新定位

    private PoiResult poiResult; // poi返回的结果
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索
    private String address;
    private String priovince, city, district;
    private List<PoiItem> list = new ArrayList<>();
    private AmapAdapter adapter;
    private LatLonPoint latLonPoint;
    private Marker marker;
    private int checkPosition;//当前选中地址的位置

    @Override
    protected void initView() {
        tvLeft.setVisibility(View.VISIBLE);
        tvTitle.setText("添加地址");
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rlDizhi.setLayoutManager(manager);
        rlDizhi.setRefreshEnabled(false);
        rlDizhi.setLoadMoreEnabled(false);
        adapter = new AmapAdapter(this, list);
        checkPosition = 0;
        adapter.setCheckPosition(0);
        rlDizhi.setAdapter(adapter);
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = map.getMap();
            initLoaction();
        }
        listener();
    }

    @Override
    protected void initData() {

    }

    private void listener() {
        //搜索
        edSousuo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String strAddress = edSousuo.getText().toString();
                if (TextUtils.isEmpty(strAddress)) {
                    Toast.makeText(AmapActivity.this, "地址不能为空", Toast.LENGTH_SHORT).show();
                    return true;
                }
                address = strAddress;
                checkPosition = 0;
                adapter.setCheckPosition(0);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        doSearchQuery();
                    }
                }).start();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(edSousuo.getWindowToken(), 0);
                return false;
            }
        });
        //适配器
        adapter.setOnItemClickListener(new SuperBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object item, int position) {
                checkPosition = position;
                adapter.setCheckPosition(position);
                adapter.notifyDataSetChanged();
                PoiItem poiItem = list.get(position);
                latLonPoint = poiItem.getLatLonPoint();
                addMarker();
            }
        });
    }

    /**
     * 初始化定位蓝点
     */
    private void initLoaction() {
        aMap.setLocationSource(this);
        aMap.setMyLocationEnabled(true);
        myLocationStyle = new MyLocationStyle();
        //初始化定位蓝点样式类
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        //设置连续定位模式下的定位间隔
        myLocationStyle.interval(2000);
        //设置定位蓝点精度圆圈的边框颜色的方法。
        myLocationStyle.strokeColor(getResources().getColor(R.color.colorEC921A));
        myLocationStyle.radiusFillColor(Color.TRANSPARENT);
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.
                fromResource(R.mipmap.dingwei));
        aMap.setMyLocationStyle(myLocationStyle);
    }


    @Override
    protected void initBefore(Bundle savedInstanceState) {
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        map.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_amap;
    }


    @OnClick({R.id.tv_left, R.id.btn_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_left:
                finish();
                break;
            case R.id.btn_sure:
                PoiItem poiItem = list.get(checkPosition);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("province", poiItem.getProvinceName());
                bundle.putString("city", poiItem.getCityName());
                bundle.putString("destrict", poiItem.getAdName());
                bundle.putString("street", poiItem.getSnippet());
                bundle.putString("address", poiItem + "");
                bundle.putDouble("latitude", poiItem.getLatLonPoint().getLatitude());
                bundle.putDouble("longitude", poiItem.getLatLonPoint().getLongitude());
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        map.onDestroy();
        super.onDestroy();
        //必须在super.onDestroy();之前使用不然第二次进去崩溃
    }

    @Override
    protected void onResume() {
        super.onResume();
        map.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        map.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        map.onSaveInstanceState(outState);
    }

    /**
     * 激活定位
     *
     * @param onLocationChangedListener
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setOnceLocationLatest(true);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置定位间隔,单位毫秒,默认为2000ms
            mLocationOption.setInterval(2000);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            mlocationClient.startLocation();//启动定位
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient = null;
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                aMap.clear();
                //地址
                address = aMapLocation.getAddress();
                city = aMapLocation.getCity();
                //将地图移动到定位点
                latLonPoint = new LatLonPoint(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()), 18));
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        doSearchQuery();
                    }
                }).start();
            }
        }
    }

    Handler hanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    adapter.notifyDataSetChanged();
                    break;
                case 1:
                    Toast.makeText(AmapActivity.this, "没有搜索到", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    /**
     * 关键字搜索
     */
    private void doSearchQuery() {
        query = new PoiSearch.Query(address, "", city);
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query) && result.getPois().size() > 0) {// 是否是同一条
                    //默认选中第一个
                    latLonPoint = result.getPois().get(0).getLatLonPoint();
                    addMarker();
                    list.clear();
                    list.addAll(result.getPois());
                    Message msg = new Message();
                    msg.what = 0;
                    hanlder.sendMessage(msg);
                } else {
                    hanlder.sendEmptyMessage(1);
                }
            }
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    /**
     * 添加覆盖物
     */
    public void addMarker() {
        //将之前的覆盖物隐藏掉
        if (marker != null) {
            marker.setVisible(false);
        }
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude()), 18));
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude()));
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.mipmap.dingwei1)));
        marker = aMap.addMarker(markerOptions);
    }

}
